<?php

namespace app\controllers;

class LogsController extends BaseController
{
    public function indexAction()
    {
        //获取文件列表
        $cacheKey = 'logs-index';
        if (!$this->view->getCache()->exists($cacheKey)) {
            $directory = str_replace('\\', '/', $this->di->get('config')->logger->path);
            if (!is_dir($directory)) {
                return '';
            }
            $fd = opendir($directory);
            if (!$fd) {
                $this->flash->error('logs dir not readable');
                return '';
            }
            $files = [];
            while (false !== ($file = readdir($fd))) {
                if (in_array($file, ['.', '..'])) {
                    continue;
                }
                $files[] = $file;
            }
            $this->view->setVar('files', $files);
            $this->view->render('logs', 'index');
            $content = $this->view->getContent();
            $this->view->getCache()->save($cacheKey, $content, 120);
        }
        $cache = $this->view->getCache()->get($cacheKey);
        return $cache;
    }

    public function getAction()
    {
        $file = $this->request->get('file');
        $fileName = str_replace('..', '', $file);
        $logPath = $this->di->get('config')->logger->path;
        $file = $logPath . '/' . $fileName;
        if (is_file($file)) {
            $op = $this->request->get('op');
            switch ($op) {
                case 'read':
                    $content = file_get_contents($file);
                    $this->view->setVar('content', $content);
                    return $this->view->render('logs', 'read');
                case 'del':
                    @unlink($file);
                    return $this->response->redirect('/logs/index');
                default:
                return $this->response->setFileToSend($file, $fileName);
            }
        }
    }
}